﻿using System;
using System.Reflection;
using MongoDB.Driver;

namespace Charisma.MongoDB
{
    internal sealed class Database : IDatabase
    {
        private readonly MongoDatabase mongoDatabase;
        private IDbProvider provider;

        public MongoDatabase Mongo
        {
            get { return mongoDatabase; }
        }

        #region IDatabase Members

        public string Name
        {
            get { return mongoDatabase.Name; }
        }

        public IRepository CreateRepository(RepositoryConfiguration configuration)
        {
            var method = typeof(Database)
                .GetMethod("CreateRepositoryInternal", BindingFlags.NonPublic | BindingFlags.Instance)
                .MakeGenericMethod(configuration.RootElement.Type);
            return (IRepository) method.Invoke(this, new object[]{configuration});
        }

        private IRepository<T> CreateRepositoryInternal<T>(RepositoryConfiguration configuration) where T : class
        {
            return new Repository<T>(provider, this, configuration);
        }

        public void Drop()
        {
            try {
                mongoDatabase.Drop();
            }
            catch (Exception e) {
                throw provider.TranslateException("Error dropping database, see inner exception for details.", e);
            }
        }

        public void Dispose()
        {
        }

        #endregion

        public Database(IDbProvider provider, MongoDatabase mongoDatabase)
        {
            this.provider = provider;
            this.mongoDatabase = mongoDatabase;
        }
    }
}